package com.itheima.nio.buffer.demo07;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NioServerDemo07 {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8383));
        serverSocketChannel.configureBlocking(false);
        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null){
                socketChannel.configureBlocking(false);
                ByteBuffer allocate = ByteBuffer.allocate(1024);
                int read = socketChannel.read(allocate);
                while (read > 0){
                    allocate.flip();
                    byte[] bytes = allocate.array();
                    System.out.println(new String(bytes, 0, read, "UTF-8"));
                    allocate.clear();
                    read = socketChannel.read(allocate);
                }
                System.out.println("接收到了客户端发送的数据....");
                ByteBuffer wrap = ByteBuffer.wrap("收到了".getBytes("UTF-8"));
                socketChannel.write(wrap);
                socketChannel.close();
            }
        }
    }
}
